import React, { useEffect, useState, useRef, useMemo } from 'react';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { useReactive } from 'ahooks';
import { StyleSheet, TouchableOpacity, View, Text, Image, TextInput, Dimensions } from 'react-native';
import { CommonStyle } from '../../../common/commonStyle.ts';
import { useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../../redux/store.ts';
import { Container, TextArea, ScrollView, Modal, Button, AlertDialog, Center, Input, Icon, Checkbox, IconButton, Avatar, Switch, Badge } from 'native-base';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import { useToast } from 'react-native-toast-notifications';
import AntDesign from 'react-native-vector-icons/AntDesign';
import CascadingPickerSelect, { TreeNode } from '../../../component/PickerCascaderSelect.tsx';
import CustomFlatList from '../../../component/CustomFlatList.tsx';
import UserRequest from '../../../request/userRequest.ts';
import HomeRequest from '../../../request/homeRequest.ts';
import Cell from '../../../component/Cell.tsx';
import GridLayout from '../../../component/GridLayout.tsx';
import Picker from '../../../component/Picker.tsx';
import EventCollection from '../../../view/tab/home/eventCollection.ts';

interface ISendNotifyProps {
  navigation: NavigationProp<any, 'sendNotify'>;
  route: RouteProp<{ sendNotify: any }, 'sendNotify'>;
}

interface INotify {
  id: string;
  name: string;
  imgUrl: string;
}

interface IData {
  notifyList: INotify[];
  selectNotify?: INotify;
  address: string;
  houseNumber: string;
  noticeType: string;
  notifyPmc: boolean;
  notifyWay: string;
  remark: string;
  strBuildIds: string;
  strFloorIds: string;
  strUnitIds: string;
  content: string;
  pickerBuildShow: boolean;
  houseNumberList: { text: string; value: string }[];
  cascader: TreeNode[]; // 选中的楼栋层数据
  cascaderData: TreeNode[]; // 楼栋层数据
  selectedBuildIds: number[]; // 选中的楼栋层ids
  params: any;
  usersInfo: {
    pageNo: number;
    pageSize: number;
    list: IBuildUserList[];
    totalPage: number;
  };
  refreshing: boolean;
  isLoading: boolean;
  pickerCommunityShow: boolean;
  showCascader: { unitName: string; floorName: string }[];
}

const SendNotify: React.FC<ISendNotifyProps> = ({ navigation, route }) => {
  const data = useReactive<IData>({
    notifyList: [
      {
        id: 'fire',
        name: '火警',
        imgUrl: 'http://pic.kanglailab.com/common/fire-alarm.png',
      },
      {
        id: 'gasLeak',
        name: '燃气泄露',
        imgUrl: 'http://pic.kanglailab.com/common/gas-alarm.png',
      },
      // {
      // 	id: 'soak',
      // 	name: "水浸溢水",
      // 	imgUrl: "http://pic.kanglailab.com/common/watersurface-alarm.png"
      // },
      {
        id: 'lockOpen',
        name: '被盗风险',
        imgUrl: 'http://pic.kanglailab.com/common/opendoor-alarm.png',
      },
      {
        id: 'sos',
        name: '紧急求助',
        imgUrl: 'https://pic.kanglailab.com/common/sos-alarm.png',
      },
      {
        id: 'fall',
        name: '洪涝灾害',
        imgUrl: 'https://pic.kanglailab.com/common/flood.png',
      },
      {
        id: 'liftFault',
        name: '电梯故障',
        imgUrl: 'https://pic.kanglailab.com/common/equip/lift_fault.png',
      },
      {
        id: 'waterOff',
        name: '停水',
        imgUrl: 'https://pic.kanglailab.com/common/equip/water_off.png',
      },
      {
        id: 'blackOut',
        name: '停电',
        imgUrl: 'https://pic.kanglailab.com/common/equip/black_out.png',
      },
      {
        id: 'other',
        name: '其他',
        imgUrl: 'https://pic.kanglailab.com/common/equip/other.png',
      },
      {
        id: 'activity',
        name: '活动',
        imgUrl: 'https://pic.kanglailab.com/common/equip/activity.png',
      },
    ],
    selectNotify: undefined,
    pickerCommunityShow: false,
    address: '',
    houseNumber: '',
    noticeType: '',
    notifyPmc: false,
    notifyWay: '',
    remark: '',
    strBuildIds: '',
    strFloorIds: '',
    strUnitIds: '',
    content: '',
    pickerBuildShow: false,
    cascader: [],
    showCascader: [],
    cascaderData: [],
    selectedBuildIds: [],
    params: {
      houseNumberId: '',
      unitId: [],
      floorId: [],
      buildId: [],
    },
    houseNumberList: [],
    usersInfo: {
      pageNo: 1,
      pageSize: 20,
      totalPage: 1,
      list: [],
    },
    refreshing: false,
    isLoading: false,
  });

  const toast = useToast();

  const beeperId = useSelector((state: RootState) => state.beeperId);

  const btnInformation = useSelector((state: RootState) => state.btnInformation); //按钮里面的数据

  const [showNotifyModal, setShowNotifyModal] = useState(false);

  const [isOpen, setIsOpen] = useState(false);

  const sendCancelRef = useRef(null);

  const [viewWidth, setViewWidth] = useState(0);

  const viewLayout = (event: any) => {
    let { x, y, width, height } = event.nativeEvent.layout;
    setViewWidth(width);
  };

  //如果只选择到了一层 获取对应children
  const findLevelThreeWithOnlyOne = (data: TreeNode[]) => {
    let levelThreeObjects = data.filter((item) => item.levels === 3);
    if (levelThreeObjects.length === 1) {
      return levelThreeObjects[0].children?.map((cItem) => {
        return {
          text: cItem.name,
          value: String(cItem.id),
        };
      });
    } else {
      return null;
    }
  };

  /**
   * 联动选择器选择
   * @param val
   * @param ids
   */
  const handleCascadingChange = (val: TreeNode[], ids: number[]) => {
    data.params.unitId = [];
    data.params.floorId = [];
    data.cascader = val;
    data.selectedBuildIds = ids;
    for (let item of data.cascader) {
      if (item.levels === 2) {
        data.params.unitId.push(item.id);
      } else if (item.levels === 3) {
        data.params.floorId.push(item.id);
      }
    }
    data.houseNumberList = findLevelThreeWithOnlyOne(data.cascader)!;
    const unitName = data.cascader.find((item) => item.levels === 2)!.name;
    // 然后，过滤出所有levels为3的项，并转换成所需格式
    data.showCascader = data.cascader.filter((item) => item.levels === 3).map((item) => ({ unitName: unitName, floorName: item.name })); // 转换为新格式
    data.pickerBuildShow = false;
  };

  /**
   * 获取该小区楼栋层
   * @param villageId
   */
  const fetchBuildingTree = (beeperId: number) => {
    UserRequest.BuildingTree({ beeperId })
      .then((res) => {
        data.cascaderData = res.data.filter((obj) => obj.id === Number(btnInformation?.linkUrl));
      })
      .catch((err) => {});
  };

  //发送通知
  const sendNotifyBtn = () => {
    if (!data.address && data.selectNotify!.id !== 'activity') {
      toast.show('请描述事故具体地址', { placement: 'bottom' });
      return false;
    }
    let params = {
      address: data.address,
      beeperId,
      btnId: btnInformation!.id,
      houseNumber: data.params.houseNumberId.names,
      noticeType: data.selectNotify?.id,
      notifyPmc: data.selectNotify?.id == 'fire' ? (data.notifyPmc == false ? 0 : 1) : 0,
      notifyWay: data.notifyWay,
      remark: data.remark,
      strBuildIds: btnInformation?.linkUrl,
      strFloorIds: data.params.floorId.join(',') || '' || '',
      strUnitIds: data.params.unitId.join(',') || '' || '',
      content: data.content,
    };
    Loading.show('通知中...');
    HomeRequest.SendInform(params)
      .then((res) => {
        if (res.data === null) {
          Loading.hide();
          toast.show('通知成功', { placement: 'bottom' });
          setIsOpen(false);
        }
      })
      .catch((err) => {
        Loading.hide();
      });
  };

  //获取栋单元层门牌号下的用户
  const getCurrentBuildUser = () => {
    Loading.show('加载中...');
    if (data.usersInfo.pageNo <= data.usersInfo.totalPage) {
      data.isLoading = true;
      let params = {
        pageNo: data.usersInfo.pageNo,
        pageSize: data.usersInfo.pageSize,
        houseNumber: data.params.houseNumberId ? data.params.houseNumberId.names : '',
        buildIds: btnInformation?.linkUrl,
        unitIds: data.params.unitId.join(',') || '' || '',
        floorIds: data.params.floorId.join(',') || '' || '',
        beeperId: beeperId,
      };
      HomeRequest.GetCurrentBuildUser(params)
        .then((res) => {
          Loading.hide();
          data.usersInfo.list = [...data.usersInfo.list, ...res.data.list];
          data.usersInfo.totalPage = res.data.totalPage;
          data.usersInfo.pageNo += 1;
          data.isLoading = false;
          data.refreshing = false;
        })
        .catch((err) => {
          Loading.hide();
          data.isLoading = false;
          data.refreshing = false;
        });
    } else {
      Loading.hide();
    }
  };

  /**
   * 选择器确认
   * @param result
   */
  const handlePickerConfirm = (result: { names: string; values: Array<string | number> }) => {
    data.params.houseNumberId = result;
    data.pickerCommunityShow = false;
  };

  //下拉刷新
  const customListRefresh = () => {
    data.refreshing = true;
    data.usersInfo.pageNo = 1;
    data.usersInfo.totalPage = 1;
    data.usersInfo.list = [];
    getCurrentBuildUser();
  };

  //点击选择楼栋层或选择门牌号的X清空数据
  const clearSelectData = (e: any, i: number) => {
    e.stopPropagation();
    if (i === 1) {
      data.selectedBuildIds = [];
      data.cascader = [];
      data.showCascader = [];
      data.params.unitId = [];
      data.params.floorId = [];
      data.houseNumberList = [];
      data.params.houseNumberId = '';
      fetchBuildingTree(beeperId);
    } else {
      data.params.houseNumberId = '';
    }
  };

  //选择门牌号
  const houseNumberChange = () => {
    if (data.houseNumberList.length === 0) {
      toast.show('请先选择单元层', { placement: 'bottom' });
      return false;
    }
    data.pickerCommunityShow = true;
  };

  useEffect(() => {
    fetchBuildingTree(beeperId);
    getCurrentBuildUser();
    setShowNotifyModal(true);
  }, []);

  const renderItem = (item: INotify, index: number) => {
    return (
      <TouchableOpacity
        onPress={() => {
          data.selectNotify = item;
          if (item.id === 'activity') data.notifyWay = '1';
          setShowNotifyModal(false);
        }}
        style={[styles.gridStyle, { width: viewWidth / 3 }]}
      >
        {item.imgUrl && (
          <Image
            style={[styles.notifyImg]}
            source={{
              uri: item.imgUrl,
            }}
          />
        )}
        <Text style={{ color: '#000', marginTop: 6, fontSize: 12, fontWeight: 'bold' }}>{item.name}</Text>
        {data.selectNotify?.id === item.id && <AntDesign name="check" style={styles.iconS} size={24} color={CommonStyle.mainColor}></AntDesign>}
      </TouchableOpacity>
    );
  };

  const renderItemUsers = (item: IBuildUserList, index: number) => {
    return (
      <View style={styles.userList}>
        <View style={styles.userBox}>
          <View style={{ flex: 0 }}>
            {item.imageUrl && (
              <Avatar
                bg="cyan.500"
                source={{
                  uri: item.imageUrl,
                }}
              ></Avatar>
            )}
          </View>
          <View style={{ flex: 1, marginLeft: 10 }}>
            <Text style={{ color: '#000', marginBottom: 8 }}>{item.nickName}</Text>
            <Text style={{ color: '#000' }}>{item.phone}</Text>
          </View>
        </View>
      </View>
    );
  };

  const LeftChild = () => {
    return (
      <View>
        <Text style={{ color: '#000' }}>通知类型</Text>
      </View>
    );
  };

  const RightChild = () => {
    return (
      <TouchableOpacity
        style={{ flexDirection: 'row', alignItems: 'center' }}
        onPress={() => {
          setShowNotifyModal(true);
        }}
      >
        <Text style={{ color: '#000', marginRight: 4 }}>{data.selectNotify?.name}</Text>
        {data.selectNotify?.imgUrl && (
          <Image
            style={styles.notifyImg}
            source={{
              uri: data.selectNotify?.imgUrl,
            }}
          />
        )}
      </TouchableOpacity>
    );
  };

  const stateShow = (type: string) => {
    switch (type) {
      case 'address':
        return (
          <View>
            {data.selectNotify?.id !== 'activity' && (
              <View style={{ flexDirection: 'row' }}>
                <Input
                  type="text"
                  w={'76%'}
                  size={'md'}
                  value={data.address}
                  InputRightElement={
                    <Icon
                      onPress={() => {
                        data.address = '';
                      }}
                      as={<MaterialIcons name="close" />}
                      size={6}
                      mr="2"
                      color="#aaa"
                    />
                  }
                  onChangeText={(e) => {
                    data.address = e;
                  }}
                  placeholder="请描述事故具体地址"
                />

                <Button
                  w={'24%'}
                  colorScheme="green"
                  onPress={() => console.log('hello world')}
                  onLongPress={() => {
                    //调用录音组件录音 ，然后录完音执行后续操作
                    // EventCollection.onLongPress(btnInformation!)
                    console.log(btnInformation);
                  }}
                  delayLongPress={500}
                >
                  语音输入
                </Button>
              </View>
            )}
            {data.selectNotify?.id === 'activity' && (
              <TextInput
                onChangeText={(e) => {
                  data.content = e;
                }}
                placeholder="请输入活动内容"
                style={styles.textAreaView}
                multiline={true}
                numberOfLines={6}
              ></TextInput>
            )}
          </View>
        );
        break;

      case 'way':
        return (
          <View>
            {data.selectNotify?.id !== 'activity' && (
              <Checkbox
                colorScheme="green"
                value={data.notifyWay}
                onChange={(e) => {
                  e ? (data.notifyWay = '1,2') : (data.notifyWay = '1');
                }}
              >
                电话+短信通知
              </Checkbox>
            )}
          </View>
        );
        break;

      case 'remark':
        return (
          <View>
            <Input
              type="text"
              w={'100%'}
              value={data.remark}
              size={'md'}
              InputRightElement={
                <Icon
                  onPress={() => {
                    data.remark = '';
                  }}
                  as={<MaterialIcons name="close" />}
                  size={6}
                  mr="2"
                  color="#aaa"
                />
              }
              onChangeText={(e) => {
                data.remark = e;
              }}
              placeholder="请填写通知备注"
            />
            {data.selectNotify?.id === 'fire' && (
              <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 10 }}>
                <View style={{ flex: 1 }}>
                  <Text style={{ color: '#000' }}>是否通知物业</Text>
                </View>
                <View style={{ flex: 1 }}>
                  <Switch
                    size="md"
                    colorScheme="green"
                    value={data.notifyPmc}
                    onChange={(e) => {
                      data.notifyPmc = e.nativeEvent.value;
                    }}
                  />
                </View>
              </View>
            )}
          </View>
        );
        break;

      case 'object':
        return (
          <View style={{ flexDirection: 'row' }}>
            <View style={{ width: '73%' }}>
              <TouchableOpacity
                onPress={() => {
                  data.pickerBuildShow = true;
                }}
                style={[styles.selectInput, { height: data.params.floorId.length === 2 ? 90 : 'auto' }]}
              >
                <AntDesign
                  name="close"
                  color={'#aaa'}
                  size={16}
                  style={{ position: 'absolute', right: 10 }}
                  onPress={(e) => {
                    clearSelectData(e, 1);
                  }}
                ></AntDesign>
                {renderCascaderTags()}
              </TouchableOpacity>
              {data.params.floorId.length < 2 && (
                <TouchableOpacity onPress={houseNumberChange} style={[styles.selectInput]}>
                  {data.params.houseNumberId ? <Text style={styles.tag}>{data.params.houseNumberId.names}</Text> : <Text>请选择门牌号</Text>}
                  <AntDesign
                    name="close"
                    color={'#aaa'}
                    size={16}
                    style={{ position: 'absolute', right: 10 }}
                    onPress={(e) => {
                      clearSelectData(e, 2);
                    }}
                  ></AntDesign>
                </TouchableOpacity>
              )}
            </View>
            <View style={{ width: '23%', marginLeft: '4%' }}>
              <TouchableOpacity
                style={[styles.searchBtn, { height: data.params.floorId.length === 2 ? 90 : 'auto' }]}
                onPress={() => {
                  getCurrentBuildUser();
                }}
              >
                <AntDesign name="search1" size={40} color={'#fff'}></AntDesign>
              </TouchableOpacity>
            </View>
          </View>
        );
        break;
    }
  };

  //渲染选择的楼栋单元层
  const renderCascaderTags = () => {
    if (data.showCascader.length > 5) {
      return data.showCascader.slice(0, 5).map((item, index) => (
        <Text style={styles.tag} key={index}>
          {index < 4 ? item.unitName + '/' + item.floorName : '...'}
        </Text>
      ));
    } else if (data.showCascader.length === 0) {
      return <Text>请选择单元层</Text>;
    } else {
      return data.showCascader.map((item, index) => (
        <Text style={styles.tag} key={index}>
          {item.unitName + '/' + item.floorName}
        </Text>
      ));
    }
  };

  //主体内容
  const mainView = useMemo(() => {
    return () => (
      <View style={styles.container}>
        <View style={{ backgroundColor: '#fff', marginBottom: 10 }}>
          <Cell isSlot={true} isBorder={false} leftChild={<LeftChild></LeftChild>} rightChild={<RightChild></RightChild>}></Cell>
        </View>
        <View style={styles.content}>
          <View style={styles.title}>
            <Text style={{ color: '#000', fontSize: 16 }}>{data.cascaderData.length > 0 && data.cascaderData[0].name}</Text>
          </View>
          <View style={styles.main}>{stateShow('address')}</View>
        </View>
        <View style={[styles.content, styles.isAlone]}>
          <View style={styles.title}>
            <Text style={{ color: '#000', fontSize: 16 }}>通知方式</Text>
            <Text style={{ color: '#000', fontSize: 12, marginTop: 6 }}>系统默认发送消息至呼吸器设备及小程序端</Text>
          </View>
          <View style={styles.main}>{stateShow('way')}</View>
        </View>
        <View style={[styles.content, styles.isAlone]}>
          <View style={styles.title}>
            <Text style={{ color: '#000', fontSize: 16 }}>通知备注</Text>
          </View>
          <View style={styles.main}>{stateShow('remark')}</View>
        </View>
        <View style={[styles.content, styles.isAlone]}>
          <View style={styles.title}>
            <Text style={{ color: '#000', fontSize: 16 }}>通知对象</Text>
          </View>
          <View style={styles.main}>{stateShow('object')}</View>
        </View>
      </View>
    );
  }, []);

  return (
    <View>
      <CustomFlatList data={data.usersInfo.list} renderItem={({ item, index }) => renderItemUsers(item, index)} ListHeaderComponent={mainView} refreshing={data.refreshing} isLoading={data.isLoading} onEndReached={getCurrentBuildUser} onRefresh={customListRefresh}></CustomFlatList>

      <TouchableOpacity
        onPress={() => {
          setIsOpen(true);
        }}
        style={styles.sendBtn}
      >
        <Text style={{ color: '#fff' }}>发 送 通 知</Text>
      </TouchableOpacity>

      {/* 组件 */}
      <CascadingPickerSelect levels={3} show={data.pickerBuildShow} data={data.cascaderData} selectedIds={data.selectedBuildIds} onClose={() => (data.pickerBuildShow = false)} onConfirm={handleCascadingChange} title={'选择楼栋层门牌号'} />

      <Picker visible={data.pickerCommunityShow} data={data.houseNumberList} onConfirm={handlePickerConfirm} onCancel={() => (data.pickerCommunityShow = false)} title={'选择门牌号'} onChange={() => (data.pickerCommunityShow = false)} />

      <Modal isOpen={showNotifyModal}>
        <Modal.Content width="90%">
          <Modal.Header alignItems={'center'}>选择通知类型</Modal.Header>
          <Modal.Body padding={0}>
            <View
              onLayout={(e) => {
                viewLayout(e);
              }}
              style={styles.gridView}
            >
              <GridLayout rowNum={3} menuList={data.notifyList} renderItem={({ item, index }) => renderItem(item, index)}></GridLayout>
            </View>
          </Modal.Body>
        </Modal.Content>
      </Modal>

      <AlertDialog leastDestructiveRef={sendCancelRef} isOpen={isOpen}>
        <AlertDialog.Content>
          <AlertDialog.CloseButton />
          <AlertDialog.Header>提示</AlertDialog.Header>
          <AlertDialog.Body>是否确认发送通知？</AlertDialog.Body>
          <AlertDialog.Footer>
            <Button.Group space={2}>
              <Button
                variant="unstyled"
                colorScheme="coolGray"
                onPress={() => {
                  setIsOpen(false);
                }}
              >
                取消
              </Button>
              <Button colorScheme="green" onPress={sendNotifyBtn}>
                确定
              </Button>
            </Button.Group>
          </AlertDialog.Footer>
        </AlertDialog.Content>
      </AlertDialog>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {},
  gridView: {
    width: '100%',
    borderRadius: 8,
  },
  gridStyle: {
    height: 80,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 8,
    position: 'relative',
  },
  notifyImg: {
    width: 30,
    height: 30,
  },
  iconS: {
    position: 'absolute',
    right: 16,
    top: 14,
  },
  content: {
    width: '100%',
    minHeight: 10,
    marginBottom: 10,
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 10,
  },
  isAlone: {
    marginBottom: 0,
    borderBottomWidth: 1,
    borderColor: '#ccc',
  },
  title: {
    marginBottom: 10,
  },
  main: {
    width: '100%',
  },
  selectInput: {
    borderWidth: 1,
    borderColor: '#ccc',
    width: '100%',
    height: 'auto',
    borderRadius: 4,
    paddingHorizontal: 6,
    paddingVertical: 6,
    position: 'relative',
    paddingRight: 30,
    marginBottom: 10,
    flexDirection: 'row',
    overflow: 'hidden',
    alignItems: 'center',
    flexWrap: 'wrap',
  },
  searchBtn: {
    backgroundColor: CommonStyle.mainColor,
    minHeight: 76,
    borderRadius: 8,
    width: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  userList: {
    paddingHorizontal: 10,
  },
  userBox: {
    backgroundColor: '#fff',
    borderRadius: 8,
    paddingVertical: 14,
    paddingHorizontal: 10,
    flexDirection: 'row',
    marginTop: 10,
  },
  textAreaView: {
    width: '100%',
    borderColor: '#ccc',
    borderWidth: 1,
    borderRadius: 8,
    textAlignVertical: 'top',
  },
  sendBtn: {
    backgroundColor: CommonStyle.mainColor,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 8,
    width: '90%',
    paddingVertical: 16,
    position: 'absolute',
    left: '5%',
    bottom: 10,
  },
  tag: {
    backgroundColor: '#ccc',
    height: 24,
    alignItems: 'center',
    marginRight: 4,
    marginBottom: 4,
    paddingHorizontal: 4,
    borderRadius: 2,
  },
});

export default SendNotify;
